package cqut.wys.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * Socket处理类，实现WebSocketHandler基础类
 * @author wuyoushan@zbj.com
 * @date 2017/3/20.
 */
@Component
public class SocketHandler implements WebSocketHandler{
//    private static final Logger logger;

    private static final ArrayList<WebSocketSession> users;

    static {
        users=new ArrayList<>();
    }

    /**
     * Websocket连接建立
     * @param webSocketSession
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        users.add(webSocketSession);
        String username=webSocketSession.getAttributes().get("user").toString();
        //判断session中用户信息
        if(username!=null){
            webSocketSession.sendMessage(new TextMessage("已成功建立Websocket通信"));
        }
    }

    /**
     * Websocket处理消息
     * @param webSocketSession
     * @param webSocketMessage
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
      //TODO
        String message=webSocketMessage.getPayload().toString();
        String id=webSocketSession.getId();
        Map<String,Object> map=webSocketSession.getAttributes();
        String userName=map.get("user").toString();
        System.out.printf("收到ID为:%s\t用户名为:%s\t发送的消息\t%s",id,userName,message);
        System.out.println();
//      System.out.println("收到:\tID为:\t"+id+"用户名为:"+userName+"发送的消息\t"+message);
    }

    /**
     * 当连接出错时，主动关闭当前连接，并从会话列表中删除该会话
     * @param webSocketSession
     * @param throwable
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        users.remove(webSocketSession);
    }

    /**
     * webSocket连接关闭
     * @param webSocketSession
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        users.remove(webSocketSession);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 给所有在线用户发送消息
     * @param message
     */
    public void sendMessageToUsers(TextMessage message){
        for (WebSocketSession user:users){
            if(user.isOpen()){
                try {
                    user.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 给某个用户发送消息
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName,TextMessage message){
        for (WebSocketSession user:users){
           if (user.getAttributes().get("user").equals(userName)){
               if (user.isOpen()){
                   try {
                       user.sendMessage(message);
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
               //结束循环
               break;
           }
        }
    }
}
